package com.china.bike.controller;

import com.alibaba.fastjson.JSON;
import com.china.bike.entity.SysFuncBean;
import com.china.bike.entity.User;
import com.china.bike.service.LoginService;
import com.china.bike.service.UserService;
import com.china.bike.utils.VerifyCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("loginController")
public class LoginController {

	@Autowired
	public LoginService loginService;

    @Autowired
    private UserService userService;

    /**
     * @param response
     * @param session
     * @throws Exception
     * @方法名: getVerifyCodeImage
     * @功能描述: 生成验证码并将验证码放入session中
     * @作者 JinJie Guo
     * @日期 2016年11月25日
     */
    @RequestMapping("/getVerifyCodeImage")
    public void getVerifyCodeImage(HttpServletResponse response, HttpSession session) throws Exception {
        //设置页面不缓存
        response.setHeader("Pragma", "no-cache");//HTTP 1.1
        response.setHeader("Cache-Control", "no-cache");//HTTP 1.0
        response.setDateHeader("Expires", 0);//设置缓存时间，0就是不缓存

        /**
         * Parameters:
         type 验证码类型,参见本类的静态属性
         length 验证码长度,要求大于0的整数
         excludeString 需排除的特殊字符（无需排除则为null）
         Returns:
         验证码字符串
         */
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);
        //将验证码字符串放入session域中
        session.setAttribute("verifyCode", verifyCode);
        /**
         * Parameters:
         textCode 文本验证码
         width 图片宽度(注意此宽度若过小,容易造成验证码文本显示不全,如4个字符的文本可使用85到90的宽度)
         height 图片高度
         interLine 图片中干扰线的条数
         randomLocation 每个字符的高低位置是否随机
         backColor 图片颜色,若为null则表示采用随机颜色
         foreColor 字体颜色,若为null则表示采用随机颜色
         lineColor 干扰线颜色,若为null则表示采用随机颜色
         Returns:
         图片缓存对象
         */
        BufferedImage generateImageCode = VerifyCodeUtil.generateImageCode(verifyCode, 80, 30, 4, true, Color.WHITE, Color.BLACK, Color.PINK);
        response.setContentType("image/jpeg");
        ImageIO.write(generateImageCode, "JPEG", response.getOutputStream());
    }

	@RequestMapping(value="login",method= RequestMethod.POST)
	public String login(@RequestParam("username")String username,
			@RequestParam("password")String password,
			@RequestParam("verifyCode")String verifyCode,
			HttpSession session,
			RedirectAttributes redirectAttributes) throws Exception{
		String attribute = (String) session.getAttribute("verifyCode");
		if (!attribute.equals(verifyCode)) {
			redirectAttributes.addFlashAttribute("errMsg", "验证码错误，请重新登陆！");
			return "redirect:/login.jsp";
		}
		User user = new User();
        user.setNickname(username);
        user.setPassword(password);
		User selectSysOpByNameOrPwd = userService.searchUser(user);
		if (selectSysOpByNameOrPwd == null) {
			redirectAttributes.addFlashAttribute("errMsg", "账号或密码输入错误，请重新登陆！");
			return "redirect:/login.jsp";
		}
		session.setAttribute("currentUser", selectSysOpByNameOrPwd);
		return "redirect:/page/index.jsp";
	}

	@RequestMapping("getMenu")
	@ResponseBody
	public List<SysFuncBean> getMenu(HttpSession session) throws Exception{
		Map<String, Object> map = new HashMap<>();
		User user = (User) session.getAttribute("currentUser");
		String[] funcIdList = user.getFuncList().split(",");
		map.put("funcList", funcIdList);
		List<SysFuncBean> list = loginService.selectFuncByOpId(map);
		List<SysFuncBean> newList = new ArrayList<>();
		for (SysFuncBean parent : list) {
			if (parent.getFuncLevel().equals(new Short("1"))) {
				List<SysFuncBean> childList = new ArrayList<>();
				for (SysFuncBean child : list) {
					if (parent.getFuncId().equals(child.getSupFuncId())) {
						childList.add(child);
					}
				}
				parent.setChildren(childList);
				newList.add(parent);
			}
		}
		System.out.println(JSON.toJSONString(newList));
		return newList;
	}
}
